<template>
  <el-dropdown @command="handleCommand" @visible-change="visibleChange">
    <span class="avatar-dropdown" :style="{ color }">
      <div class="user-name">
        {{ userInfo.userName }}
        <svg-icon :name="isShowIcon ? 'top-s' : 'below-s'" size="12px" color="#fff" class="icon"></svg-icon>
      </div>
    </span>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item command="personCenter" divided>个人中心</el-dropdown-item>
        <el-dropdown-item command="logOut" divided>退出登录</el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script>
export default {
  name: 'UserInfo',
};
</script>

<script setup>
import { defineProps, computed, ref } from 'vue';
import { useStore } from 'vuex';
import { setting } from '@/config/setting';
import { useRouter } from 'vue-router';
import { ElMessageBox } from "element-plus";
const { title } = setting;
const store = useStore();
const router = useRouter();

defineProps({
  color: {
    type: String,
    default: '#fff',
  },
});

const isShowIcon = ref(false)


const userInfo = computed(() => {
  return store.getters['user/userInfo'];
})

const visibleChange = (type) => {
  isShowIcon.value = type
}
const handleCommand = (command) => {
  switch (command) {
    case 'personCenter':
      router.push({ name: 'PersonCenter', query: { type: 1 } }).catch(() => { });
      break;
    case 'logOut':
      handleLogout();
      break;
    default:
      break;
  }
};

const handleLogout = () => {
  ElMessageBox.confirm(`您确定要退出${title}？`, '操作提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    dangerouslyUseHTMLString: true,
    type: 'warning',
  })
    .then(async () => {
      router.push({ path: `/login` })
      await store.dispatch('user/logOut', sessionStorage.onlineToken).then((res) => {
        if (res) {
          router.push({ path: `/login` }).catch(() => { });
        }
      });
    })
    .catch(() => { });
};
</script>

<style lang="scss" scoped>
.avatar-dropdown {
  display: flex;
  align-content: center;
  align-items: center;
  justify-content: center;
  justify-items: center;
  height: $base-avatar-dropdown-height;
  padding: 0 $base-padding-10 0 $base-padding-10;
  cursor: pointer;
}
</style>
